<template>
    <div class="profile-container">
        <div class="header">
            <h1>个人资料管理</h1>
            <p class="slogan">完善您的信息，享受更好的环保服务</p>
        </div>
        
        <div class="profile-box">
            <el-tabs v-model="activeTab" type="card">
                <el-tab-pane label="基本信息" name="basic">
                    <div class="form-section">
                        <h3><i class="el-icon-user"></i> 基本资料</h3>
                        <el-form 
                            :model="userForm" 
                            :rules="userRules"
                            ref="userForm"
                            label-width="100px"
                            class="profile-form"
                        >
                            <el-form-item label="姓名" prop="name">
                                <el-input v-model="userForm.name"></el-input>
                            </el-form-item>
                            <el-form-item label="手机号" prop="phone">
                                <el-input v-model="userForm.phone" disabled></el-input>
                            </el-form-item>
                            <el-form-item label="身份证号" prop="idCardNum">
                                <el-input v-model="userForm.idCardNum"></el-input>
                            </el-form-item>
                            <el-form-item label="邮箱" prop="email">
                                <el-input v-model="userForm.email"></el-input>
                            </el-form-item>
                            <el-form-item label="身份证验证">
                                <div class="id-card-verification">
                                    <div class="upload-section">
                                        <div class="upload-box">
                                            <el-upload
                                                class="id-card-upload"
                                                action="#"
                                                :http-request="uploadIdCardFront"
                                                :show-file-list="false"
                                                :before-upload="beforeIdCardUpload"
                                            >
                                                <div class="upload-area" v-if="!idCardFrontUrl">
                                                    <i class="el-icon-plus"></i>
                                                    <div class="upload-text">上传身份证正面</div>
                                                </div>
                                                <div v-else class="preview-container">
                                                    <img :src="idCardFrontUrl" class="id-card-preview" />
                                                    <div class="preview-overlay">
                                                        <i class="el-icon-delete" @click.stop="removeIdCardImage('front')"></i>
                                                    </div>
                                                </div>
                                            </el-upload>
                                            <div class="upload-label">身份证正面</div>
                                        </div>
                                        
                                        <div class="upload-box">
                                            <el-upload
                                                class="id-card-upload"
                                                action="#"
                                                :http-request="uploadIdCardBack"
                                                :show-file-list="false"
                                                :before-upload="beforeIdCardUpload"
                                            >
                                                <div class="upload-area" v-if="!idCardBackUrl">
                                                    <i class="el-icon-plus"></i>
                                                    <div class="upload-text">上传身份证反面</div>
                                                </div>
                                                <div v-else class="preview-container">
                                                    <img :src="idCardBackUrl" class="id-card-preview" />
                                                    <div class="preview-overlay">
                                                        <i class="el-icon-delete" @click.stop="removeIdCardImage('back')"></i>
                                                    </div>
                                                </div>
                                            </el-upload>
                                            <div class="upload-label">身份证反面</div>
                                        </div>
                                    </div>
                                    
                                    <div class="verification-status">
                                        <el-tag v-if="verificationStatus === 'success'" type="success">
                                            <i class="el-icon-check"></i> 身份验证通过
                                        </el-tag>
                                        <el-tag v-else-if="verificationStatus === 'failed'" type="danger">
                                            <i class="el-icon-close"></i> 身份验证失败
                                        </el-tag>
                                        <el-tag v-else-if="verificationStatus === 'pending'" type="warning">
                                            <i class="el-icon-loading"></i> 验证中...
                                        </el-tag>
                                        <el-tag v-else type="info">
                                            <i class="el-icon-info"></i> 未验证
                                        </el-tag>
                                        
                                        <el-button 
                                            type="primary" 
                                            size="small" 
                                            @click="verifyIdCard"
                                            
                                        >
                                            验证身份
                                        </el-button>
                                    </div>
                                    
                                    <div class="verification-result" v-if="verificationResult">
                                        <div class="result-title">验证结果：</div>
                                        <div class="result-content">
                                            <div v-if="verificationResult.name">
                                                <span class="result-label">姓名：</span>
                                                <span>{{ verificationResult.name }}</span>
                                            </div>
                                            <div v-if="verificationResult.idNumber">
                                                <span class="result-label">身份证号：</span>
                                                <span>{{ verificationResult.idNumber }}</span>
                                            </div>
                                            <div v-if="verificationResult.address">
                                                <span class="result-label">地址：</span>
                                                <span>{{ verificationResult.address }}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="success" @click="updateBasicInfo">保存修改</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-tab-pane>
                
                <el-tab-pane label="地址管理" name="address">
                    <div class="form-section">
                        <h3><i class="el-icon-location"></i> 地址信息</h3>
                        
                        <div class="address-list" v-if="addresses.length > 0">
                            <el-card v-for="(address, index) in addresses" :key="index" class="address-card">
                                <div class="address-info">
                                    <div class="address-header">
                                        <span class="address-name">{{ address.detailedAddress }}</span>
                                        <el-tag size="small" type="success" v-if="address.isDefault==1">默认地址</el-tag>
                                    </div>
                                </div>
                                <div class="address-actions">
                                    <el-button 
                                        type="text" 
                                        @click="setDefaultAddress(index)"
                                        v-if="!address.isDefault"
                                    >设为默认</el-button>
                                    <el-button type="text" @click="editAddress(index)">编辑</el-button>
                                    <el-button type="text" @click="deleteAddress(index)">删除</el-button>
                                </div>
                            </el-card>
                        </div>
                        
                        <div class="empty-address" v-else>
                            <i class="el-icon-location-information"></i>
                            <p>您还没有添加地址</p>
                        </div>
                        
                        <el-button 
                            type="success" 
                            icon="el-icon-plus" 
                            @click="showAddressDialog = true"
                            class="add-address-btn"
                        >添加新地址</el-button>
                    </div>
                </el-tab-pane>
                
                <el-tab-pane label="安全设置" name="security">
                    <div class="form-section">
                        <h3><i class="el-icon-lock"></i> 密码修改</h3>
                        <el-form 
                            :model="passwordForm" 
                            :rules="passwordRules"
                            ref="passwordForm"
                            label-width="100px"
                            class="profile-form"
                        >
                            <el-form-item label="原密码" prop="oldPassword">
                                <el-input 
                                    v-model="passwordForm.oldPassword" 
                                    type="password"
                                    show-password
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="新密码" prop="newPassword">
                                <el-input 
                                    v-model="passwordForm.newPassword" 
                                    type="password"
                                    show-password
                                ></el-input>
                            </el-form-item>
                            <el-form-item label="确认密码" prop="confirmPassword">
                                <el-input 
                                    v-model="passwordForm.confirmPassword" 
                                    type="password"
                                    show-password
                                ></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="success" @click="updatePassword">修改密码</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
        
        <!-- 地址选择对话框 -->
        <el-dialog 
            title="地址信息" 
            :visible.sync="showAddressDialog" 
            width="80%"
            :before-close="handleDialogClose"
            @opened="handleDialogOpened"
        >
            <el-form :model="addressForm" :rules="addressRules" ref="addressForm" label-width="100px">
                <el-form-item label="收件人" prop="name">
                    <el-input v-model="addressForm.name" placeholder="请输入收件人姓名"></el-input>
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="addressForm.phone" placeholder="请输入联系电话"></el-input>
                </el-form-item>
                <el-form-item label="选择位置" prop="location">
                    <div class="map-container" id="map-container">
                        <MapContainer @location-update="handleLocationUpdate" ref="mapComponent"></MapContainer>
                    </div>
                </el-form-item>
                <el-form-item label="详细地址" prop="detail">
                    <el-input 
                        v-model="addressForm.detail" 
                        type="textarea" 
                        :rows="2"
                        placeholder="请输入详细地址信息，如门牌号、小区名等"
                        :value="addressForm.province + addressForm.city + addressForm.district + addressForm.street"
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-checkbox v-bind="addressForm.isDefault" @change="handleDefaultChange">设为默认地址</el-checkbox>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showAddressDialog = false">取 消</el-button>
                <el-button type="success" @click="saveAddress">保 存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import MapContainer from '@/components/MapContainer.vue'

export default {
    name: 'UserProfile',
    components: {
        MapContainer
    },
    data() {
        // 确认密码验证
        const validateConfirmPassword = (rule, value, callback) => {
            if (value !== this.passwordForm.newPassword) {
                callback(new Error('两次输入的密码不一致'));
            } else {
                callback();
            }
        };
        
        return {
            activeTab: 'basic',
            showAddressDialog: false,
            editingAddressIndex: -1, // -1表示新增，>=0表示编辑
            
            // 用户基本信息
            userForm: {
                name: '',
                phone: '',
                idCardNum: '',
                email: ''
            },
            userRules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' }
                ],
                idCardNum: [
                    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
                ],
                email: [
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ]
            },
            
            // 密码修改
            passwordForm: {
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            },
            passwordRules: {
                oldPassword: [
                    { required: true, message: '请输入原密码', trigger: 'blur' }
                ],
                newPassword: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
                ],
                confirmPassword: [
                    { required: true, message: '请再次输入新密码', trigger: 'blur' },
                    { validator: validateConfirmPassword, trigger: 'blur' }
                ]
            },
            
            // 地址信息
            addresses: [],
            addressForm: {
                userId:null,
                name: '',
                phone: '',
                province: '',
                city: '',
                district: '',
                street: '',
                detail: '',
                lng: '',
                lat: '',
                isDefault: 0
            },
            addressRules: {
                name: [
                    { required: true, message: '请输入收件人姓名', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                detail: [
                    { required: true, message: '请输入详细地址', trigger: 'blur' }
                ]
            },
            // 添加身份证验证相关数据
            idCardFrontUrl: '',
            idCardBackUrl: '',
            idCardFrontFile: null,
            idCardBackFile: null,
            verificationStatus: 'none', // none, pending, success, failed
            verificationResult: null,
        }
    },
    mounted() {
        
        this.getAddressList();
    },
    methods: {
        handleDefaultChange(val) {
            this.addressForm.isDefault = val ? 1 : 0
        },
        // getAddressInfo(){
        //     const encodedAddress = encodeURIComponent(this.addressForm.detail);
        //     fetch(`https://restapi.amap.com/v3/geocode/geo?address=${encodedAddress}&output=json&key=ef690c3fa49486fff79b9ed58d6ee0ab`)
        //         .then(response => {
        //             if (!response.ok) {
        //                 throw new Error('网络响应不正常');
        //             }
        //             return response.json(); // 将响应解析为JSON
        //         })
        //         .then(data => {
        //             console.log('解析后的数据:', data);
        //             if (data.status === '1') {
        //                 if (data.geocodes.length > 1) {
        //                     // 如果返回多个地点，弹出选择框
        //                     this.$confirm('', '请选择地址', {
        //                         confirmButtonText: '确定',
        //                         cancelButtonText: '取消',
        //                         showCancelButton: false,
        //                         customClass: 'address-select-dialog',
        //                         message: h => {
        //                             return h('div', [
        //                                 h('p', { style: 'margin-bottom: 10px' }, '找到多个地址，请选择一个:'),
        //                                 h('el-radio-group', {
        //                                     props: { value: 0 },
        //                                     on: { input: val => this.selectedAddressIndex = val }
        //                                 }, data.geocodes.map((item, index) => {
        //                                     return h('el-radio', {
        //                                         props: { label: index },
        //                                         style: 'display: block; margin: 10px 0'
        //                                     }, [
        //                                         `${item.formatted_address} (${item.province} ${item.city} ${item.district || ''})`,
        //                                         h('div', { style: 'color: #666; font-size: 12px; margin-left: 24px' }, [
        //                                             `行政区划: ${item.adcode}`,
        //                                             h('br'),
        //                                             `坐标: ${item.location}`
        //                                         ])
        //                                     ])
        //                                 }))
        //                             ])
        //                         }
        //                     }).then(() => {
        //                         const selected = data.geocodes[this.selectedAddressIndex];
        //                         this.addressForm.lng = selected.location.split(',')[0];
        //                         this.addressForm.lat = selected.location.split(',')[1];
        //                         this.addressForm.province = selected.province;
        //                         this.addressForm.city = selected.city;
        //                         this.addressForm.district = selected.district;
        //                         this.addressForm.detail = selected.formatted_address;
        //                         this.$message.success('已选择地址并填充表单');
        //                     }).catch(() => {
        //                         this.$message.info('已取消选择');
        //                     });
        //                 } else {
        //                     // 只有一个地址时直接填充
        //                     const geocode = data.geocodes[0];
        //                     this.addressForm.lng = geocode.location.split(',')[0];
        //                     this.addressForm.lat = geocode.location.split(',')[1];
        //                     this.addressForm.province = geocode.province;
        //                     this.addressForm.city = geocode.city;
        //                     this.addressForm.district = geocode.district;
        //                     this.addressForm.detail = geocode.formatted_address;
        //                     this.$message.success('获取地址信息成功，已将地址信息填入表单');
        //                 }
        //             } else {
        //                 this.$message.warning('地址解析失败：' + (data.info || '未知错误'));
        //             }
        //         })
        //         .catch(error => {
        //             console.error('获取地址信息失败:', error);
        //             this.$message.error('获取地址信息失败，请检查网络连接或地址格式');
        //         });
        // },
        // 获取用户信息
        async getUserInfo() {
            try {
                const userId = localStorage.getItem('userId');
                if (!userId) {
                    this.$message.warning('请先登录');
                    this.$router.push('/login');
                    return;
                }
                
                const response = await this.$http.get('/userService/user/getUserInfo', {
                    params: { userId }
                });
                
                if (response.data.code === 200) {
                    const userData = response.data.data;
                    this.userForm = {
                        name: userData.name || '',
                        phone: userData.phone || '',
                        idCardNum: userData.idCardNum || '',
                        email: userData.email || ''
                    };
                } else {
                    this.$message.error(response.data.message || '获取用户信息失败');
                }
            } catch (error) {
                this.$message.error('获取用户信息失败');
                console.error(error);
            }
        },
        
        // 更新基本信息
        async updateBasicInfo() {
            try {
                this.$refs.userForm.validate(async (valid) => {
                    if (valid) {
                        const userId = localStorage.getItem('userId');
                        const params = {
                            ...this.userForm,
                            userId
                        };
                        
                        const response = await this.$http.post('/userService/user/updateUserInfo', params);
                        
                        if (response.data.code === 200) {
                            this.$message.success('更新成功');
                        } else {
                            this.$message.error(response.data.message || '更新失败');
                        }
                    }
                });
            } catch (error) {
                this.$message.error('更新失败');
                console.error(error);
            }
        },
        
        // 修改密码
        async updatePassword() {
            try {
                this.$refs.passwordForm.validate(async (valid) => {
                    if (valid) {
                        const userId = localStorage.getItem('userId');
                        const params = {
                            userId,
                            oldPassword: this.passwordForm.oldPassword,
                            newPassword: this.passwordForm.newPassword
                        };
                        
                        const response = await this.$http.post('/userService/user/updatePassword', params);
                        
                        if (response.data.code === 200) {
                            this.$message.success('密码修改成功');
                            this.passwordForm = {
                                oldPassword: '',
                                newPassword: '',
                                confirmPassword: ''
                            };
                        } else {
                            this.$message.error(response.data.message || '密码修改失败');
                        }
                    }
                });
            } catch (error) {
                this.$message.error('密码修改失败');
                console.error(error);
            }
        },
        
        // 获取地址列表
        async getAddressList() {
            try {
                const userId = localStorage.getItem('userId');
                if (!userId) return;
                
                const response = await this.$http.get('/userService/address/selectAddressByUserId', {
                    params: { userId }
                });
                
                if (response.data.code === 200) {
                    this.addresses = response.data.data || [];
                } else {
                    this.$message.error(response.data.message || '获取地址列表失败');
                }
            } catch (error) {
                this.$message.error('获取地址列表失败');
                console.error(error);
            }
        },
        
        // 处理地图位置更新
        handleLocationUpdate(location) {
            console.log('UserProfile 接收到位置更新:', JSON.stringify(location));
            this.addressForm.province = location.city || '';
            this.addressForm.city = location.district || '';
            this.addressForm.district = location.street || '';
            this.addressForm.lng = location.lng || '';
            this.addressForm.lat = location.lat || '';
            
            // 直接将完整地址填入详细地址输入框
            if (location.fullAddress) {
                console.log('使用完整地址:', location.fullAddress);
                this.addressForm.detail = location.fullAddress;
            } else if (location.detail) {
                console.log('使用部分地址:', location.detail);
                this.addressForm.detail = location.detail;
            }
            
            console.log('更新后的地址表单:', JSON.stringify(this.addressForm));
        },
        
        // 保存地址
        async saveAddress() {
            try {
                this.$refs.addressForm.validate(async (valid) => {
                    if (valid) {
                        this.addressForm.userId = localStorage.getItem('userId');
                        const regex = /^(.*?省|.*?市|.*?自治区)(.*?市|.*?自治州|.*?区|.*?县|.*?旗)(?:.*?)(.*)$/;
                        console.log('地址'+this.addressForm.detail);
                        let match = this.addressForm.detail.match(regex);
                        console.log('是否匹配正则'+match);
                        if (match) {
                            const city = match[1];
                            const district = match[2];
                            const street = match[3] ? match[3].split(' ')[0] : ''; // 尝试提取街道信息
                            const detail = match[3] ? (match[3].split(' ').length > 1 ? match[3].split(' ')[1] : match[3]) : match[3]; // 提取详细地址
                            
                            console.log('省/直辖市:', city);
                            console.log('区县:', district);
                            console.log('街道:', street);
                            console.log('详细地址:', detail);
                            
                            this.addressForm.address = this.address
                            this.addressForm.city = city
                            this.addressForm.district = district
                            
                            // 如果有街道信息则分别设置street和detail
                            if (street) {
                                this.addressForm.street = street;
                                this.addressForm.detail = detail;
                            } else {
                                // 如果没有街道信息，则将整个剩余部分设为detail
                                this.addressForm.detail = match[3];
                            }
                            
                            console.log(this.addressForm);
                        } else {
                            console.log('地址格式不正确');
                        }
                        this.$http.post('/userService/address/addAddress',this.addressForm).then(resp=>{
                            console.log(resp);
                            if (resp.data.code === 200) {
                                this.$message.success('保存地址成功');
                                this.showAddressDialog = false;
                                this.getAddressList(); // 刷新地址列表
                                window.location.reload(); // 刷新页面
                            } else {
                                this.$message.error(resp.data.message || '保存地址失败');
                            }
                        })
                        
                        // 如果是编辑模式
                        if (this.editingAddressIndex >= 0) {
                            params.id = this.addresses[this.editingAddressIndex].id;
                            url = '/userService/address/update';
                            successMsg = '更新地址成功';
                        }                        
                    }
                });
            } catch (error) {
                this.$message.error('保存地址失败');
                console.error(error);
            }
        },
        
        // 编辑地址
        editAddress(index) {
        console.log('下标'+index)
            this.editingAddressIndex = index;
            this.addressForm = this.addresses[index];
            // this.addressForm = { ...address };
            this.showAddressDialog = true;
        },
        
        // 删除地址
        async deleteAddress(index) {
            try {
                this.$confirm('确定要删除这个地址吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const addressId = this.addresses[index].id;
                    const response = await this.$http.post('/userService/address/delete', {
                        id: addressId
                    });
                    
                    if (response.data.code === 200) {
                        this.$message.success('删除地址成功');
                        this.getAddressList(); // 刷新地址列表
                    } else {
                        this.$message.error(response.data.message || '删除地址失败');
                    }
                }).catch(() => {
                    // 取消删除
                });
            } catch (error) {
                this.$message.error('删除地址失败');
                console.error(error);
            }
        },
        
        // 设置默认地址
        async setDefaultAddress(index) {
            try {
                const addressId = this.addresses[index].id;
                const userId = localStorage.getItem('userId');
                
                const response = await this.$http.post('/userService/address/setDefault', {
                    id: addressId,
                    userId
                });
                
                if (response.data.code === 200) {
                    this.$message.success('设置默认地址成功');
                    this.getAddressList(); // 刷新地址列表
                } else {
                    this.$message.error(response.data.message || '设置默认地址失败');
                }
            } catch (error) {
                this.$message.error('设置默认地址失败');
                console.error(error);
            }
        },
        
        // 关闭对话框
        handleDialogClose() {
            this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.showAddressDialog = false;
                this.resetAddressForm();
            }).catch(() => {
                // 取消关闭
            });
        },
        
        // 重置地址表单
        resetAddressForm() {
            this.editingAddressIndex = -1;
            this.addressForm = {
                name: '',
                phone: '',
                province: '',
                city: '',
                district: '',
                street: '',
                detail: '',
                lng: '',
                lat: '',
                isDefault: 0
            };
            if (this.$refs.addressForm) {
                this.$refs.addressForm.resetFields();
            }
        },
        
        // 对话框打开后初始化地图
        handleDialogOpened() {
            // 给地图容器一点时间来渲染
            setTimeout(() => {
                if (this.$refs.mapComponent) {
                    this.$refs.mapComponent.initMap();
                }
            }, 300);
        },
        // 身份证上传前验证
        beforeIdCardUpload(file) {
            const isImage = file.type.startsWith('image/');
            const isLt5M = file.size / 1024 / 1024 < 5;

            if (!isImage) {
                this.$message.error('请上传图片文件!');
                return false;
            }
            if (!isLt5M) {
                this.$message.error('图片大小不能超过 5MB!');
                return false;
            }
            return true;
        },
        
        // 上传身份证正面
        uploadIdCardFront(options) {
            this.idCardFrontFile = options.file;
            this.createImagePreview(options.file, 'front');
        },
        
        // 上传身份证反面
        uploadIdCardBack(options) {
            this.idCardBackFile = options.file;
            this.createImagePreview(options.file, 'back');
        },
        
        // 创建图片预览
        createImagePreview(file, type) {
            const reader = new FileReader();
            reader.onload = (e) => {
                if (type === 'front') {
                    this.idCardFrontUrl = e.target.result;
                } else {
                    this.idCardBackUrl = e.target.result;
                }
            };
            reader.readAsDataURL(file);
        },
        
        // 验证身份证
        async verifyIdCard() {
            if (!this.idCardFrontFile || !this.idCardBackFile) {
                this.$message.warning('请上传身份证正反面照片');
                return;
            }
            
            this.verificationStatus = 'pending';
            
            // try {
                const formData = new FormData();
                // formData.append('frontImage', this.idCardFrontFile); 
                console.log(this.idCardBackFile);
                formData.append('idCard', this.idCardBackFile);
                console.log(formData);
                const response = await this.$http.post('http://localhost:8088/userService/user/recognizeIdCard', formData);
                
                if (response.data.code === 200) {
                    this.verificationStatus = 'success';
                    this.verificationResult = response.data.data;
                    
                    // 自动填充身份证信息
                    if (this.verificationResult) {
                        if (this.verificationResult.name) {
                            this.userForm.name = this.verificationResult.name;
                        }
                        if (this.verificationResult.idNumber) {
                            this.userForm.idCardNum = this.verificationResult.idNumber;
                            // 禁用身份证号输入框
                            this.$refs.userForm.fields.find(field => field.prop === 'idCardNum')
                                .disabled = true;
                        }
                        // 添加头像和昵称
                        if (this.verificationResult.avatar) {
                            this.userForm.avatar = this.verificationResult.avatar;
                        }
                        if (this.verificationResult.nickname) {
                            this.userForm.nickname = this.verificationResult.nickname;
                        }
                    }
                    
                    this.$message.success('身份验证成功');
                } else {
                    this.verificationStatus = 'failed';
                    this.$message.error(response.data.message || '身份验证失败');
                }
            // } catch (error) {
            //     this.verificationStatus = 'failed';
            //     this.$message.error('身份验证失败，请稍后重试');
            //     console.error(error);
            // }
        },
        // 添加删除图片方法
        removeIdCardImage(type) {
            if (type === 'front') {
                this.idCardFrontUrl = '';
                this.idCardFrontFile = null;
            } else {
                this.idCardBackUrl = '';
                this.idCardBackFile = null;
            }
            // 重置验证状态
            if (this.verificationStatus === 'success' || this.verificationStatus === 'failed') {
                this.verificationStatus = 'none';
                this.verificationResult = null;
            }
        }
    }
}
</script>

<style scoped>
.profile-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
    min-height: 100vh;
    background-color: #f0f9eb;
}

.header {
    text-align: center;
    margin-bottom: 30px;
    padding: 20px 0;
}

.header h1 {
    color: #67c23a;
    font-size: 2.5em;
    margin-bottom: 10px;
}

.slogan {
    color: #606266;
    font-size: 1.2em;
    font-style: italic;
}

.profile-box {
    background: white;
    border-radius: 15px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 30px;
}

.form-section {
    margin-top: 20px;
}

h3 {
    color: #67c23a;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 8px;
}

h3 i {
    font-size: 1.2em;
}

.profile-form {
    max-width: 600px;
}

.map-container {
    height: 400px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

.address-list {
    margin-bottom: 20px;
}

.address-card {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.address-info {
    flex: 1;
}

.address-header {
    margin-bottom: 10px;
}

.address-name {
    font-weight: bold;
    margin-right: 15px;
}

.address-phone {
    color: #606266;
    margin-right: 15px;
}

.address-detail {
    color: #606266;
    line-height: 1.5;
}

.address-actions {
    display: flex;
    gap: 10px;
}

.empty-address {
    text-align: center;
    padding: 40px 0;
    color: #909399;
}

.empty-address i {
    font-size: 48px;
    margin-bottom: 10px;
}

.add-address-btn {
    margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .profile-container {
        padding: 10px;
    }

    .header h1 {
        font-size: 2em;
    }

    .profile-box {
        padding: 15px;
    }

    .map-container {
        height: 300px;
    }

    .address-card {
        flex-direction: column;
        align-items: flex-start;
    }

    .address-actions {
        margin-top: 10px;
        width: 100%;
        justify-content: flex-end;
    }
}

/* 添加身份证验证相关样式 */
.id-card-verification {
    margin-top: 10px;
}

.upload-section {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
}

.upload-box {
    flex: 1;
    max-width: 240px; /* 稍微加宽以适应身份证横向比例 */
    text-align: center;
}

.id-card-upload {
    width: 100%;
}

.upload-area {
    width: 100%;
    height: 140px;
    aspect-ratio: 1.6 / 1; /* 身份证标准比例 */
    max-height: 140px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: border-color 0.3s;
}

.upload-area:hover {
    border-color: #67c23a;
}

.upload-area i {
    font-size: 28px;
    color: #8c939d;
}

.upload-text {
    color: #8c939d;
    margin-top: 8px;
}

.upload-label {
    margin-top: 8px;
    color: #606266;
}

.id-card-preview {
    width: 100%;
    height: 100%;
    object-fit: contain; /* 改为contain以保持图片比例 */
    background-color: #f5f5f5;
}

.verification-status {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 15px;
}

.verification-result {
    background-color: #f8f8f8;
    padding: 15px;
    border-radius: 6px;
    margin-top: 15px;
}

.result-title {
    font-weight: bold;
    margin-bottom: 10px;
    color: #303133;
}

.result-content {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.result-label {
    font-weight: bold;
    color: #606266;
    margin-right: 5px;
}

.preview-container {
    position: relative;
    width: 100%;
    height: 140px;
    border-radius: 6px;
    overflow: hidden;
}

.preview-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s;
}

.preview-container:hover .preview-overlay {
    opacity: 1;
}

.preview-overlay i {
    font-size: 24px;
    color: #fff;
    cursor: pointer;
    padding: 8px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.2);
}

.preview-overlay i:hover {
    background-color: rgba(255, 255, 255, 0.3);
    transform: scale(1.1);
}
</style> 